#include "btl_config.h"
#include "fp_timer.h"
#include "fp_log.h"
#include "fp_task.h"
#include "fingerprint.h"

/*
 * The following is the core logic that need wait for finger down.
 * such as: do_capture(), do_verify(), do_enroll().
 *
 * 1. task_run(TASK_ID_WFD, do_capture)
 * 2. wait until task_tfd() triggered, this indicates finger is down.
 * 3. do_capture()/do_verify()/do_enroll() and others.
 * 4. if task_tfd() triggered, next task is TASK_ID_IDLE.
 */

// static btl_rc_t btl_result_old = BTL_RC_OK;
static btl_rc_t btl_result = BTL_RC_OK;

void bfxx_fingerprint_task()
{
    TIME_MEASURE_INIT(task_time);
    fp_task_t* task = fp_task();
    uint16_t task_time;

    do {
        /* TASK_ID_IDLE */
        if (IS_FP_TASK(task, task_id, TASK_ID_IDLE)) {
            task_default();
            // break;
        }

        /* TASK_ID_WFD
         * All the following tasks are only executed when finger is down.
         * setup the following tasks by task_run(TASK_ID_WFD, do_XXX):
         * 1. do_capture()
         * 2. do_verify()
         * 3. do_enroll()
         */
        TIME_MEASURE_UPDATE(task_time);
        btl_result = btl_finger_detect_ex();

        // if (btl_result == 0)
        {

            task_time = TIME_MEASURE_DIFFOF(task_time);
            // if (btl_result == 0)
            //     bf_print_d("finger detect time: %u", task_time);

            /* keep the result of finger detect to task_fd */
            SET_FP_TASK(task, task_fd, btl_result);
            SET_FP_TASK(task, task_time, task_time);
        }
    } while (0);

    /* Try to do the task:
     *  1. check if task_tfd() triggered, this indicates finger is down.
     *  2. if task_tfd() triggered, todo algorithm action, such as capture, verify, enroll.
     */
    task->run();

    /* Try to do the next task:
     *  1. if task_tfd() triggered, next task is TASK_ID_IDLE.
     *  2. Otherwise, nothing to do.
     */
    task_next();
}
